package com.ost.kautilya.modeling.weka;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

import javax.management.AttributeNotFoundException;

import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Utils;

import com.ost.kautilya.modeling.ModelConfiguration;
import com.ost.kautilya.modeling.ModelConfigurationParameter;
import com.ost.kautilya.modeling.ModelMetaData;
import com.ost.kautilya.modeling.Model.ModelType;
import com.ost.kautilya.modeling.ModelParameters;

public class WekaOptions extends ModelConfiguration {

	private static final long serialVersionUID = 1L;
	public static final String CONFIGURATION_DEFINITION = "WEKA - CL OPTIONS";

	@Override
	public String getDefinitionFor(ModelMetaData meta) {
		return CONFIGURATION_DEFINITION + " for " + (meta.getType() == ModelType.CLUSTERING ? meta.getParameter(ModelParameters.CLUSTERER) : meta.getParameter(ModelParameters.CLASSIFIER));
	}

	public WekaOptions(OptionHandler oh) {
		super();
		Enumeration<?> opts = oh.listOptions();
		List<String> ao = new ArrayList<String>();
		String optS = "";
		for (String aov : oh.getOptions()) {
			String[] aoa = aov.split(" ");
			ao.addAll(Arrays.asList(aoa));
			optS += " " + aov;
		}
		// System.out.println(optS);
		try {
			String[] aoa = Utils.splitOptions(optS);
			ao = Arrays.asList(aoa);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// System.out.println(ao);
		List<Integer> flags = new ArrayList<Integer>();
		List<Integer> args = new ArrayList<Integer>();
		List<Integer> skipped = new ArrayList<Integer>();
		while (opts.hasMoreElements()) {
			Option opt = (Option) opts.nextElement();
			try {
				int index = ao.indexOf("-" + opt.name());
				ModelConfigurationParameter option = new WekaOption(index, opt, ao);
				if (option.isAvailable()) {
					if (option.isFlag() && "true".equalsIgnoreCase(option.getDefaultValue())) {
						flags.add(index);
					} else if (!option.isFlag()) {
						args.add(index);
						args.add(index + 1);
					} else {
						skipped.add(index);
					}
					put(option, option.getDefaultValue());
				}
			} catch (AttributeNotFoundException e) {

			}
		}
		// System.out.println(ao.size());
		// System.out.println(flags);
		// System.out.println(args);
		// System.out.println(skipped);
		if ((ao.size() - flags.size()) > args.size()) {
			String val = "";
			int ui = -1;
			for (int i = 0; i < ao.size(); i++) {
				if (!flags.contains(i) && !args.contains(i) && !skipped.contains(i)) {
					val += " " + ao.get(i);
					ui = i + 1;
					ui = ui == ao.size() || flags.contains(ui) || args.contains(ui) || skipped.contains(ui) ? i - 1 : -1;
				}
				if (ui >= 0) {
					ModelConfigurationParameter blank = new ModelConfigurationParameter(ui, "", "Additional options", val.trim(), false, true);
					put(blank, blank.getDefaultValue());
					val = "";
					ui = -1;
				}
			}
		}
	}
}
